package com.psychologyCommunity.Community.Contoller;

import com.psychologyCommunity.Community.entity.Event;
import com.psychologyCommunity.Community.entity.Page;
import com.psychologyCommunity.Community.entity.User;
import com.psychologyCommunity.Community.event.EventProducer;
import com.psychologyCommunity.Community.service.FollowService;
import com.psychologyCommunity.Community.service.UserService;
import com.psychologyCommunity.Community.util.CommunityConstance;
import com.psychologyCommunity.Community.util.CommunityUtil;
import com.psychologyCommunity.Community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class FollowController implements CommunityConstance {
    @Autowired
    private FollowService followService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    @Autowired
    private EventProducer eventProducer;
    @RequestMapping(path = "/follow",method = RequestMethod.POST)
    @ResponseBody
    public String follow(int entityType,int entityId){
        //如果没登录 就应该设置一个拦截器做检查，强制让他登录之后才能访问
        User user = hostHolder.getUser();

        //我执行关注，肯定是当前登录的用户作为粉丝
        followService.follow(user.getId(),entityType,entityId);
        //触发关注事件 --某某某关注了你，关注是关注某个人，是链接到这个人的 主页上
        Event event=new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);//目前只能关注人 ，entityId
        //此时不需要链接到 帖子上 所以不需要 .setData("postId",postId);
        eventProducer.fireEvent(event);
        //关注之后要给页面返回一个异步的请求
        return CommunityUtil.getJSONString(0,"关注成功！！");
    }

    @RequestMapping(path = "/unfollow",method = RequestMethod.POST)
    @ResponseBody
    public String unfollow(int entityType,int entityId){
        //如果没登录 就应该设置一个拦截器做检查，强制让他登录之后才能访问
        User user = hostHolder.getUser();

        //我执行关注，肯定是当前登录的用户作为粉丝
        followService.Unfollow(user.getId(),entityType,entityId);


        //关注之后要给页面返回一个异步的请求
        return CommunityUtil.getJSONString(1,"取消关注！！");
    }
    //要查询某个用户关注的人
    @RequestMapping(path = "/followees/{userId}",method = RequestMethod.GET)
    public String getFollowees(@PathVariable("userId") int userId, Page page, Model model){
        User user = userService.findUserById(userId);
        if(user ==null){
            throw new RuntimeException("该用户不存在");
        }
        //传用户的原因 是因为标签上会显示用户的信息
        model.addAttribute("user",user);
        page.setLimit(5);
        page.setPath("/followees/"+userId);
        page.setRows((int) followService.findFolloweeCount(userId , ENTITY_TYPE_USER));
        List<Map<String,Object>> userList=followService.findFollowees(userId,page.getSetOff(),page.getLimit());
        //如果用户列表不为空，我们才去遍历 ，遍历是要 hasFollowed（）判断 当前用户 对这些 目标用户关注过 了
        if(userList !=null){
            for(Map<String,Object> map:userList){
                User targetUser=(User) map.get("user");
                map.put("hasFollowed",hasFollowed(targetUser.getId()));//放入标志 ，来标注是否是已关注的用户--相当于补充模板中的数据
            }
            model.addAttribute("users",userList);
        }
        return "/site/followee";
    }
    //判断当前用户是否已经关注了 userId为id的用户
    public boolean hasFollowed(int userId){
        if(hostHolder.getUser() ==null){
            return false;
        }
        return followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
    }

    //要查询某个用户粉丝
    @RequestMapping(path = "/followers/{userId}",method = RequestMethod.GET)
    public String getFollowers(@PathVariable("userId") int userId, Page page, Model model){
        User user = userService.findUserById(userId);
        if(user ==null){
            throw new RuntimeException("该用户不存在");
        }
        //传用户的原因 是因为标签上会显示用户的信息
        model.addAttribute("user",user);
        page.setLimit(5);
        page.setPath("/followers/"+userId);
        page.setRows((int) followService.findFollowerCount(ENTITY_TYPE_USER,userId));
        List<Map<String,Object>> userList=followService.findFollower(userId,page.getSetOff(),page.getLimit());
        //如果用户列表不为空，我们才去遍历 ，遍历是要 hasFollowed（）判断 当前用户 对这些 目标用户关注过 了
        if(userList !=null){
            for(Map<String,Object> map:userList){
                User targetUser=(User) map.get("user");
                map.put("hasFollowed",hasFollowed(targetUser.getId()));//放入标志 ，来标注是否是已关注的用户--相当于补充模板中的数据
            }
            model.addAttribute("users",userList);
        }
        return "/site/follower";
    }
}
